package net.kevin.db.mapper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.persistence.Column;

public class MapperTool {
	public static void mapper(ResultSet rs, Object model) {
		try {
			Field[] fields = model.getClass().getDeclaredFields();
			for (Field f : fields) {
				Column anno = f.getAnnotation(Column.class);
				if (anno != null) {
					String columnName = anno.name();
					Class<?> type = f.getType();
					String columnValue = null;
					if (columnName.equals("DATA_DEFAULT")) {
						columnValue = InputStreamToString(rs.getAsciiStream("DATA_DEFAULT"));
					} else {
						columnValue = String.valueOf(rs.getObject(columnName));
					}
					if (type.getName().equals(String.class.getName())) {
						String setter = "set" + f.getName().substring(0, 1).toUpperCase() + f.getName().substring(1);
						model.getClass().getMethod(setter, type).invoke(model, columnValue);
					}
				}
			}
			try {
				model.getClass().getMethod("afterSet").invoke(model);
			} catch (Exception e) {
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	private static String InputStreamToString(InputStream is) throws SQLException, IOException {
		if(is == null)
			return null;
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		String line = null;
		StringBuilder sb = new StringBuilder();
		while((line = reader.readLine()) != null){
			sb.append(line);
		}
		return sb.toString();
	}
}
